import { logout } from 'auto-provider'
import { useAuth } from 'context/auth-context'
import qs from 'qs'
import { useCallback } from 'react'
const apiURL = process.env.REACT_APP_API_URL

interface IfetchConfig extends RequestInit {
  data?: object
  token?: string
}

export const http = (endPoniter: string, { data, token, headers, ...otherConfig }: IfetchConfig = {}) => {
  const config = {
    method: 'GET',
    headers: {
      'Content-Type': data ? 'application/json' : '',
      Authorization: token ? `Bearer ${token}` : ''
    },
    ...otherConfig
  }

  if (config.method.toUpperCase() === 'GET') {
    endPoniter += `?${qs.stringify(data)}`
  } else {
    config.body = JSON.stringify(data || {})
  }
  return window.fetch(`${apiURL}/${endPoniter}`, config).then(async response => {
    // 如果 token失效, 登出
    if (response.status === 401) {
      await logout()
      window.location.reload()
      return Promise.reject({ message: '请重新登录' })
    }
    const data = await response.json()
    if (response.ok) {
      return data
    } else {
      return Promise.reject(data)
    }
  })
}

export const useHttp = () => {
  const { user } = useAuth()
  // 只有当用户token改变时再重新请求数据
  return useCallback(
    (...[endPoniter, config]: Parameters<typeof http>) => http(endPoniter, { ...config, token: user?.token }),
    [user?.token]
  )
}
